package com.fruit.service.task;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fruit.constants.TaskConstant;
import com.fruit.pojo.task.TaskLog;
import com.fruit.service.log.TaskLogManager;
import com.fruit.service.notice.NoticeMessageManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @ClassName: MailBackJob
 * @author shibeilei
 * @version 2017.11.30 16:40
 */
@Slf4j
@Service("noticeMessageJob")
public class NoticeMessageJob {

	@Autowired
	private TaskLogManager taskLogService;
	
	@Autowired
	private NoticeMessageManager noticeMessageService;

	/**
	 * 寄回通知调度
	 */
	public void pluckNoticeJob() {
		String tradeId = CommonUtil.getUUID();
		String notifyTime = DateUtil.getDay();
		log.info("[{}]-【采摘通知-任务调度】-【开始】-【日期：{}】", tradeId, notifyTime);
		TaskLog tl = null;
		try {
			tl = taskLogService.insertTaskLog(tradeId, "采摘通知-任务调度", DateUtil.getTime());
			if (tl != null) {
				Map<String, Object> resMap = noticeMessageService.sendNoticeMessage(tradeId, notifyTime);
				ResultInfo result = (ResultInfo) resMap.get("result");
				if (ResultInfo.SUCCESS.equals(result.getState())) {
					tl.setState(TaskConstant.LogState.success.getValue());
					log.info("[{}]-【采摘通知-任务调度】-【成功】", tradeId);
				} else {
					tl.setState(TaskConstant.LogState.fail.getValue());
					log.error("[{}]-【采摘通知-任务调度】-【失败】", tradeId);
				}
				tl.setEndTime(DateUtil.getTime());
				tl.setCode(result.getCode());
				tl.setMessage(result.getMessage());
			}
		} catch (Exception e) {
			log.error("[{}]-【采摘通知-任务调度】-【异常】----{}", tradeId, CustomUtil.getStackTraceAsString(e));
			if (tl != null) {
				tl.setState(TaskConstant.LogState.fail.getValue());
				tl.setEndTime(DateUtil.getTime());
				tl.setCode("exception");
				tl.setMessage("采摘通知-任务调度-异常");
			}
		} finally {
			log.info("[{}]-【采摘通知-任务调度】-【结束】", tradeId);
			if (tl != null) {
				taskLogService.updateTaskLog(tl);
			}
		}

	}

}
